﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NHibernate;
using DotNet.Common.NHibernateUtil;
using ZLCMS.Data.Model;
using ZLCMS.Business.Util;
using System.Collections;
using NHibernate.Transform;

namespace ZLCMS.Web.PayChannal.Code
{
    public class PaymentRequireBase : ZLCMS.Web.Wap.Code.MemberPageBase
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            PaymentNo = Request["pno"];

            using(ISession session = SessionFactoryHelper.CreateSession())
            {
                //检查支付信息是否正常
                IList<IDictionary> orderDatas = session.CreateSQLQuery("select order_no,CANCEL_STATUS,pay_status,member_account,order_time from shop_order_info where payment_no=:pno")
                    .SetParameter("pno", PaymentNo)
                    .SetResultTransformer(Transformers.AliasToEntityMap)
                    .List<IDictionary>();
                foreach (IDictionary item in orderDatas)
                {
                    if (Convert.ToInt32(item["CANCEL_STATUS"]) == 0 && Convert.ToInt32(item["pay_status"]) == 0 && item["member_account"] as string == CurrentMemberAccount)
                    {
                        //只能对自己的状态正常的订单支付
                    }
                    else
                    {
                        Response.Write("支付信息异常，请稍后重试。");
                        Response.End();
                        return;
                    }
                    OrderTime = Convert.ToDateTime(item["order_time"]);
                }
                int minutes = Convert.ToInt32(ParamKit.GetValue("SystemConfig", "OrderTimeout", "60"));
                ExpireTime = OrderTime.AddMinutes(minutes);

                PaymentPrice = session.CreateSQLQuery("select sum(PAYMENT_FEE) from shop_order_info where payment_no=:pno")
                    .SetParameter("pno", PaymentNo)
                    .UniqueResult<decimal>();

                PaymentInfo = session.Get<ShopPaymentInfo>(Int32.Parse(Request["pid"]));
                
                IList<string> pnlist = session.CreateSQLQuery("select p.product_name from shop_order_info o inner join shop_order_product p on o.order_no=p.order_no where o.payment_no=:pno ")
                    .SetParameter("pno", PaymentNo)
                    .List<string>();

                if (pnlist.Count == 0)
                {
                    Response.Write("您的订单支付超时，请稍后重试。");
                    Response.End();
                    return;
                }

                foreach (string pn in pnlist)
                {
                    ProductDesc += "【" + pn + "】";
                }
                if (ProductDesc.Length > 20)
                {
                    ProductDesc = ProductDesc.Substring(0, 20) + "...";
                }
            }

            if (string.IsNullOrEmpty(PaymentNo) || PaymentPrice <= 0 || PaymentInfo == null)
            {

                Response.Write("数据异常，请稍后重试。");
                Response.End();
                //获取openid
                //string openid = (string)Session[GlobalSessionString.WxPayTempOpenId];

                //if (string.IsNullOrEmpty(openid))
                //{
                //    Response.Redirect("/Wap/Shop/Default.aspx");
                //}
                //else
                //{
                //    Response.Redirect("/wap/shop/OrderList.aspx");
                //}
            }

        }

        /// <summary>
        /// 返回带参数的完整路径，注意路径不能带参数
        /// </summary>
        /// <param name="nativeUrl">原始路径，不用带域名</param>
        /// <returns></returns>
        public string GetCallbackUrl(string nativeUrl)
        {
            string url = ServerUtil.GetRootURI() + nativeUrl;
            //if (url.IndexOf("?") == -1)
            //{
            //    url += "?pid=" + PaymentInfo.Id;
            //}
            //else
            //{
            //    url += "&pid=" + PaymentInfo.Id;
            //}
            return url;
        }

        public string GetNoncestr()
        {
            return Guid.NewGuid().ToString("N");
        }


        public long GetTimestamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds);
        }

        protected void ReportError(string msg)
        {
            Response.Write(msg);
            Response.End();
        }

        protected string ProductDesc { get; set; }

        /// <summary>
        /// 支付信息
        /// </summary>
        protected ShopPaymentInfo PaymentInfo { get; set; }

        /// <summary>
        /// 支付编码
        /// </summary>
        protected string PaymentNo { get; set; }

        /// <summary>
        /// 订单费用
        /// </summary>
        protected decimal PaymentPrice { get; set; }

        protected DateTime OrderTime { get; set; }

        protected DateTime ExpireTime { get; set; }
    }
}